import LocalStorageUtil from "@/utils/local-storage-util";
import store from "@/store";
import {RouterActionsEnum} from "@/store/enum/store.enum";

const state = () => ({
	//用户信息
	userInfo: LocalStorageUtil.getObjectItem('userInfo'),

	//token信息
	token: LocalStorageUtil.getItem('token'),

	//菜单列表
	menuList: LocalStorageUtil.getObjectItem('menuList'),

	// 上一个登录的用户
	prevUser:'',
})
const mutations = {
    userInfo: (userState, data) => {
        //需先存菜单数据
        LocalStorageUtil.addItem('menuList', data.treeMenus);
        LocalStorageUtil.addItem('token', data.accessToken);
        userState.menuList = data.treeMenus;
        userState.token = data.accessToken;

        //把菜单数据剔除
        delete data.treeMenus;

        //存储用户信息
        LocalStorageUtil.addItem('userInfo', data);
        userState.userInfo = data;
        // 菜单组件使用routes中存储数据
        store.dispatch(RouterActionsEnum.setRoutes);
    },

    //更新菜单数据
	updateMenuList: (userState, data) => {
		LocalStorageUtil.updateItem('menuList', data);
		userState.menuList = data;
	},
	// 清除登录信息
	clearUserInfo: (userState) => {
		// 保留上次登录的用户名
		userState.prevUser = userState.userInfo.username;
		LocalStorageUtil.deleteItem('userInfo');
		LocalStorageUtil.deleteItem('token');
		LocalStorageUtil.deleteItem('menuList');
		userState.token = null;
		userState.userInfo = null;
		userState.menuList = null;
	},
	// 清除上次登录的用户记录
	clearPrevUser:(userState)=>{
		userState.prevUser = '';
	}
}
const getters = {
    userInfo(userState) {
        return userState.userInfo;
    },
	token(userState) {
		return userState.token;
	},
	menuList(userState) {
		return userState.menuList;
	},
	prevUser(userState){
		return userState.prevUser;
	}
}
const actions = {
	// 清除登录信息
	clearUserInfo({commit}){
		commit('clearUserInfo')
	},
	// 清除登录信息
	clearPrevUser({commit}){
		commit('clearPrevUser')
	}

}
export default {state, getters, mutations, actions}
